package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.enums.BompImageFileOprTypeEnum;
import cc.rengu.igas.bomp.facade.enums.BompImageTypeEnum;
import cc.rengu.igas.bomp.facade.request.ImageFileUpDownloadRequest;
import cc.rengu.igas.bomp.facade.request.MchntImageInfoQueryRequest;
import cc.rengu.igas.bomp.facade.response.ImageFileUpDownloadResponse;
import cc.rengu.igas.bomp.facade.response.MchntImageInfoQueryResponse;
import cc.rengu.redp.bizimpl.enums.BompQueryTypeEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntImageInfo;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntBaseInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntImageInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.ImageInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-22
 */

@Slf4j
@Api(tags = "商户管理:商户影像信息管理")
@RestController
@RequestMapping("/admin/mcmp/bMchntImageInfo")
public class BMchntImageInfoController extends BaseController {
    @Autowired
    private IUpmpBMchntImageInfoService bMchntImageInfoService;
    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;
    @DubboReference(version = "${dubbo.protocol.version}", check = false)
//    @DubboReference(version = "2.2.0",url = "dubbo://172.17.100.9:62132",check = false)
    private BompMchntManageService bompMchntManageService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

//    @DubboReference(version = "2.2.0", url = "dubbo://172.17.100.9:62132", check = false)
    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntQueryService bompQueryService;


    @RequiresPermissions("商户管理:统一支付平台商户管理")
    @GetMapping(value = "/list")

    public Map<String, Object> findByPage(QueryRequest request, UpmpBMchntImageInfo entity) {
        return getDataTable(bMchntImageInfoService.findByPage(request, entity));
    }


    @RequiresPermissions("商户管理:统一支付平台商户管理")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)

    public OperationResult editSave(@ModelAttribute("bMchntImageInfo") UpmpBMchntImageInfo entity, Model model) {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        this.bMchntImageInfoService.saveOrUpdate(entity);
        result.put("id", entity.getId());
        //TODO 添加实际业务操作
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    @RequiresPermissions("商户管理:统一支付平台商户管理")
    @DeleteMapping("/{ids}")
    @ApiImplicitParam(paramType = "path", name = "ids", value = "id主键，逗号隔开", required = true, dataType = "String")
    public void delete(@NotBlank(message = "{required}") @PathVariable String ids) throws RedpException {
        try {
            this.bMchntImageInfoService.getBaseMapper().deleteBatchIds(Arrays.asList(ids.split(StringPool.COMMA)));
        } catch (Exception e) {
            String message = "删除失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    /**
     * 获取图片流传输给页面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */

    @GetMapping(value = "/getBompImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imgId", value = "图片标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imageType", value = "图片类型", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "fileType", value = "logo", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imageLocalPath", value = "图片路径", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "queryType", value = "1正式表0临时表", required = true, dataType = "String")
    })
    public OperationResult getImg(HttpServletRequest request, HttpServletResponse response) throws RedpException {
        String imgId = request.getParameter("imgId") == null ? "" : request.getParameter("imgId");
        String imageType = request.getParameter("imageType") == null ? "" : request.getParameter("imageType");
        String instId = request.getParameter("instId") == null ? "" : request.getParameter("instId");
        String fileType = request.getParameter("fileType") == null ? "" : request.getParameter("fileType");
        String imageLocalPath = request.getParameter("imageLocalPath") == null ? "" : request.getParameter("imageLocalPath");
        String queryType = request.getParameter("queryType") == null ? "" : request.getParameter("queryType");
        OperationResult operationResult = new OperationResult(OperationResult.OPERATION_RESULT_TYPE.failure,"获取图片失败");
        if (Common.isNotBlank(imageType)||Common.isNotBlank(fileType)) {

            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
            if(StringUtils.isNotBlank(imageType)){
                req.setImageType(imageType);
            }else {
                req.setFileType(fileType);
            }
            req.setOprType("01");
            req.setId(imgId);
            req.setUserId(user.getId());
            req.setImageLocalPath(imageLocalPath);
            operationResult = bMchntBaseInfoService.imageFileUpDownload(instId, req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), queryType);
            ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
            if(StringUtils.isNotBlank(resp.getImageData())){
                String path = new String(Base64.getDecoder().decode(resp.getImageLocalPath()));
                String fileSuffix = path.substring(path.lastIndexOf(".") + 1);
                resp.setImageData("data:image/" + fileSuffix + ";base64," + resp.getImageData());
            }
        }
        return operationResult;
    }

    /**
     * 附件下载
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imgId", value = "图片标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imageType", value = "图片类型", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imageDesc", value = "图片描述", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "queryType", value = "1正式表0临时表", required = true, dataType = "String")
    })
    @GetMapping(value = "/downFile")
    public void downFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, RedpException {
        String imgId = request.getParameter("imgId") == null ? "" : request.getParameter("imgId");
        String imageType = request.getParameter("imageType") == null ? "" : request.getParameter("imageType");
        String instId = request.getParameter("instId") == null ? "" : request.getParameter("instId");
        String queryType = request.getParameter("queryType") == null ? "" : request.getParameter("queryType");
        String imageDesc = request.getParameter("imageDesc") == null ? "" : request.getParameter("imageDesc");
        imageDesc = URLEncoder.encode(imageDesc, "UTF-8");
        if (Common.isNotBlank(imgId) && Common.isNotBlank(imageType)) {

            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
            req.setImageType(imageType);
            req.setOprType("01");
            req.setId(imgId);
            req.setUserId(user.getId());
            OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(instId, req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
//
            if (operationResult.getType().equals(OperationResult.OPERATION_RESULT_TYPE.success.name())) {

                OutputStream out = null;
                try {
                    ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
//                    String ImageLocalPath =  new String(Base64.getDecoder().decode(resp.getImageLocalPath()));

                    byte[] b = Base64.getDecoder().decode(resp.getImageData());
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }

                    String fileName1 = resp.getImageLocalPath().substring(resp.getImageLocalPath().lastIndexOf(File.separator) + 1);
                    String fileName = "新建 Microsoft Word 97 - 2003 文档.doc";

                    //设置发送到客户端的响应内容类型
                    response.setContentType("application/x-msdownload;");
                    response.setHeader("Content-disposition", "attachment; filename=" + new String(imageDesc.getBytes("utf-8"), "ISO8859-1"));
                    response.setHeader("Content-Length", String.valueOf(b.length));
                    out = response.getOutputStream();
                    out.write(b);
                    out.flush();
//                    response.flushBuffer();
                    //关闭响应输出流
                    out.close();
                } catch (Exception ex) {
                    log.error("获取文件失败", ex);
                    throw new RedpException("获取文件失败" + ex.getCause());
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            log.error("关闭响应输出流失败", e);
                        }
                    }
                }

            }
        }
    }

    /**
     * 调用联机接口进行文件上传
     *
     * @param request
     * @param fileUpload
     * @return
     */

    @RequestMapping(value = "/uploadBomp", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "imageType", value = "图片类型", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "fileType", value = "logo", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mchntNo", value = "商户号", required = true, dataType = "String")
    })
    public OperationResult imageUpload(HttpServletRequest request, @RequestParam(value = "imgFile",required=false) MultipartFile fileUpload, HttpServletResponse response) throws RedpException {
        String mchntNo = request.getParameter("mchntNo");
        String imageType = request.getParameter("imageType");
        String fileType = request.getParameter("fileType");
        String instId = request.getParameter("instId");
        try {
            if (fileUpload != null && !fileUpload.isEmpty()) {
                log.debug("multei file upload ====== file.size = " + fileUpload.getSize());
                String name = fileUpload.getOriginalFilename();
                if (StringUtils.isNotBlank(name)) {
                    String suffix = name.substring(name.lastIndexOf(".") + 1);
                    if (BusinessContainer.WHITE_IMAGE_SUFFIX.indexOf(suffix.trim().toLowerCase()) < 0) {
                        throw new RedpException("上传文件格式必须为" + BusinessContainer.WHITE_IMAGE_SUFFIX + "等，请重新提交");
                    }
                }
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
                req.setImageData(java.util.Base64.getEncoder().encodeToString(fileUpload.getBytes()));
                if(StringUtils.isNotBlank(imageType)){
                    req.setImageType(imageType);
                }else {
                    req.setFileType(fileType);
                }
                req.setOprType(BompImageFileOprTypeEnum.UPLOAD.getType());//默认上传
                req.setMchntNo(mchntNo);
                req.setUserId(user.getId());
                req.setImageName(fileUpload.getOriginalFilename());
                OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(instId, req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
                HttpSession session = request.getSession();
                ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
                session.setAttribute("imageData", resp.getImageData());
                // HSTS响应头
                response.setHeader("Strict-Transport-Security", "max-age=31536000");
                //
                response.setContentType(MediaType.TEXT_PLAIN_VALUE + "; charset=UTF-8");
                return operationResult;
            } else {
                return OperationResult.buildFailureResult( "未获取到文件");
            }
        } catch (IOException e) {
//            throw new RedpException("Upload file error", e);
            log.error("Upload file error", e);
            return OperationResult.buildFailureResult( "上传图片失败");
        }
    }

    @RequestMapping(value = "/uploadBomp/singlefile", method = RequestMethod.POST)

    public void singleFileUpload(HttpServletRequest request, @RequestParam("fileUpload") CommonsMultipartFile fileUpload, HttpServletResponse response) throws RedpException, IOException {        //将控件ID传入
        String elId = request.getParameter("elId");
        String elIndex = request.getParameter("imageIndex");
        String mchntNo = request.getParameter("mchntNo");
        String instId = request.getParameter("instId");
        try {
            if (fileUpload != null && !fileUpload.isEmpty()) {
                String name = fileUpload.getOriginalFilename();

                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
                req.setImageData(java.util.Base64.getEncoder().encodeToString(fileUpload.getBytes()));
                req.setImageType("00");
                req.setOprType("00");
                req.setMchntNo(mchntNo);
                req.setUserId(user.getId());
                req.setImageName(fileUpload.getOriginalFilename());
                OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(instId, req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
                if (operationResult.getType().equals("success")) {
                    operationResult.setMessage(name);
                }
                operationResult.setRedirect(elId + elIndex);
                operationResult.setRedirect(elId + elIndex);
                response.setContentType(MediaType.TEXT_PLAIN_VALUE + "; charset=UTF-8");
                response.getWriter().print(JSON.toJSONString(operationResult));
            } else {
            }
        } catch (Exception e) {
            log.error("Upload file error", e);
        }
    }


    /**
     * 商户影像下载
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    @RequestMapping(value = "/zip")
    public void zip(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, RedpException {
        //查询商户影像信息
        String mchntNo = request.getParameter("mchntNo");
        String instId = request.getParameter("instId");
        String type = request.getParameter("type");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        MchntImageInfoQueryRequest reqQry = new MchntImageInfoQueryRequest();
        reqQry.setMchntNo(mchntNo);
        reqQry.setUserId(user.getId());
        MchntImageInfoQueryResponse resp = null;
        ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
        String queryType = null;
        if (type.equals(BompQueryTypeEnum.TEMP.getType())) {
            resp = bMchntImageInfoService.mchntImageInfoQuery(instId, reqQry, bompQueryService, bMchntBaseInfoService.genMerOrder(user.getInstId()), BompQueryTypeEnum.TEMP);
            queryType = "0";
        } else {
            resp = bMchntImageInfoService.mchntImageInfoQuery(instId, reqQry, bompQueryService, bMchntBaseInfoService.genMerOrder(user.getInstId()), BompQueryTypeEnum.REAL);
            queryType = "1";
        }

        List<ImageInfoVO> mchntImagList = bMchntImageInfoService.getmchntImageList(resp);

        req.setMchntNo(mchntNo);
        req.setOprType("01");
        req.setImageType("00");

        req.setUserId(user.getId());

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("商户影像", "UTF-8") + ".zip");
        response.setCharacterEncoding("UTF-8");
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        for (ImageInfoVO imageinfovo : mchntImagList) {

            req.setId(imageinfovo.getId());
            req.setImagePath(imageinfovo.getImageLocalPath());

            OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(instId, req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), queryType);

            if (operationResult.getCode().equals("100000")) {
                try {
                    ImageFileUpDownloadResponse imag = (ImageFileUpDownloadResponse) operationResult.getData();
                    byte[] b = Base64.getDecoder().decode(imag.getImageData());
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {
                            b[i] += 256;
                        }
                    }
                    ByteArrayInputStream in = new ByteArrayInputStream(b);
                    zos.putNextEntry(new ZipEntry(imageinfovo.getName()));
                    int temp = 0;
                    if ((temp = in.read()) != -1) {
                        zos.write(b);
                    }
                    in.close();
                } catch (Exception ex) {
                    log.error("获取图片失败", ex);
                    throw new RedpException("获取图片失败" + ex.getCause());
                }

            }

        }
        if (null != zos) {
            zos.flush();
            zos.close();
        }

    }
}
